<template>
  <div v-if="props.charData && props.charData.length > 0" class="gcharts" id="bar">
  </div>
  <app-loading v-else />
</template>
<script setup>
import { Chart } from '@antv/g2';
import { nextTick, reactive, watch } from 'vue';

const props = defineProps({
  charData: {
    type: Array,
    default: () => {
      return [];
    },
  },
  type: Number,
})
const state = reactive({
  chart: null
})
const drawChart = () => {
  //创建chart
  state.chart = new Chart({
    container: 'bar',
    forceFit: true,
    width: 780,
    height: 350,
    padding: [30, 20, 20, 20]
  })
  // 载入数据源
  state.chart.data(props.charData);
  state.chart.legend({
    position: 'top-right'
  });
  state.chart.interval().position('type*value').color('name').adjust([{
    type: 'dodge',
    marginRatio: 1 / 32
  }]);;
  // 渲染图表
  state.chart.render();
}
watch(
  () => props.charData,
  (newVal, oldVal) => {
    if (state.chart) {
      // 销毁画布对象
      state.chart.destroy();
    }
    if (newVal) {
      nextTick(() => {
        drawChart();
      });
    }
  }
);
</script>
<style lang="scss" scoped>
.gcharts {
  width: 100%;
  height: 100%;
}
</style>